package com.lv.drawable.drawable

import android.graphics.drawable.Drawable
import android.graphics.drawable.StateListDrawable

class SelectorBuilder {

    private var defaultDraw: Drawable? = null
    private var defaultBuilder: (() -> Drawable)? = null
    private var builders = mutableListOf<StateBuilder>()

    fun defState(drawable: Drawable): SelectorBuilder = apply {
        defaultDraw = drawable
    }

    fun defState(builder: () -> Drawable): SelectorBuilder = apply {
        defaultBuilder = builder
    }

    fun addState(state: StateElement, drawable: Drawable): SelectorBuilder = apply {
        builders.add(StateBuilder(state).drawable(drawable))
    }

    fun addState(state: StateElement, builder: () -> Drawable): SelectorBuilder = apply {
        builders.add(StateBuilder(state).drawable(builder))
    }

    fun build(): StateListDrawable {
        val stateListDrawable = StateListDrawable()
        for (builder in builders) {
            stateListDrawable.addState(builder.stateElement.states, builder.drawable ?: builder.drawableBuilder?.invoke())
        }
        val defaultDraw = defaultDraw ?: defaultBuilder?.invoke()
        if (defaultDraw != null) {
            stateListDrawable.addState(intArrayOf(), defaultDraw)
        }
        return stateListDrawable
    }

    class StateBuilder(val stateElement: StateElement) {
        var drawable: Drawable? = null
        var drawableBuilder: (() -> Drawable)? = null

        fun drawable(builder: () -> Drawable) = apply {
            drawableBuilder = builder
        }

        fun drawable(draw: Drawable) = apply {
            drawable = draw
        }
    }
}